home *** CD-ROM | disk | FTP | other *** search
- Path: spock.ebt.com!gtn
- From: gtn@ebt-inc (Gavin Nicol)
- Newsgroups: comp.lang.c
- Subject: Re: Counting high bits (was (no subject))
- Date: 02 Mar 1996 15:12:22 GMT
- Organization: Electronic Book Technologies, Inc.
- Distribution: world
- Message-ID: <GTN.96Mar2101222@ebt-inc>
- References: <4gv493$p09@nuacht.iol.ie> <4h5bin$i2t@ccshst05.cs.uoguelph.ca>
- NNTP-Posting-Host: ebt-inc.ebt.com
- In-reply-to: thay@uoguelph.ca's message of 29 Feb 1996 23:07:03 GMT
-
- If you know the size of the data that you are trying to count bits in,
- a simple way is to use a table. This is also quite fast.
-
- /*
- * count bits using a table
- */
-
- static char bit_table[256] = {
- 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
- 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
- 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
- 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
- 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
- 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
- 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
- 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
- };
-
- int count_bits_table(unsigned long x)
- {
- unsigned char *ptr = (unsigned char *)&x;
-
- return(bit_table[ptr[0]] + bit_table[ptr[1]] +
- bit_table[ptr[2]] + bit_table[ptr[3]] );
- }
-
- The most esoteric one I have ever seen is HACKMEM, for X11 source code:
-
- int count_bits_hackmem(unsigned long x)
- {
- register unsigned long tmp;
-
- tmp = (x >> 1) &033333333333;
- tmp = x - tmp - ((tmp >>1) & 033333333333);
- return ((unsigned int) (((tmp + (tmp >> 3)) & 030707070707) % 077));
- }
- --
-
- Gavin Thomas Nicol | He who will not reason, is a bigot;
- Electronic Book Technologies | he who cannot is a fool;
- Email: gtn@ebt.com | and he who dares not is a slave.
- Phone/FAX: +81-3-3706-7351 | --- Sir William Drummond
-
-